package com.ushier.shop.drugstore.dao;

import com.ushier.shop.drugstore.bean.Drug;
import com.ushier.shop.drugstore.db.DBHelper;
import com.ushier.shop.drugstore.util.BeanUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DrugDAO {

    private DBHelper helper = new DBHelper();


    public boolean insert(String name, String desc, BigDecimal price, String pic){
        String sql = "INSERT INTO _drug (name, `desc`, price, pic) VALUES(?, ?, ?, ?)";
        int update = helper.update(sql, new Object[]{name, desc, price, pic});
        return update > 0;
    }

    public boolean update(int id, String name, String desc, BigDecimal price, String pic){
        String sql = "UPDATE _drug SET name = ?, `desc` = ?, price = ?, pic = ? WHERE id = ?";
        int update = helper.update(sql, new Object[]{name, desc, price, pic, id});
        return update > 0;
    }

    public boolean delete(int id){
        String sql = "DELETE FROM _drug WHERE id = ?";
        int update = helper.update(sql, new Object[]{id});
        return update > 0;
    }

    public Drug get(int id){
        String sql = "SELECT id, name, `desc`, price, pic FROM _drug WHERE id = ?";
        List<Map<String, Object>> list = helper.query(sql, new Object[]{id});
        if(null == list || list.isEmpty()){
            return null;
        }
        return BeanUtil.mapToObject(list.get(0), Drug.class);
    }

    public List<Drug> list(){
        String sql = "SELECT id, name, `desc`, price, pic FROM _drug";
        List<Map<String, Object>> list = helper.query(sql);
        if(null == list || list.isEmpty()){
            return null;
        }

        List<Drug> retList = new ArrayList<>();
        list.forEach(map -> {
            retList.add(BeanUtil.mapToObject(map, Drug.class));
        });

        return retList;
    }

}
